using SqlSugar;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using EasyAdmin.Admin.Entity.Entities;

namespace EasyAdmin.Admin.Entity.DbContext
{
    /// <summary>
    /// SqlSugar 数据库上下文配置
    /// </summary>
    public static class SqlSugarDbContext
    {
        /// <summary>
        /// 注册 SqlSugar 服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddSqlSugar(this IServiceCollection services, IConfiguration configuration)
        {
            var connectionString = configuration.GetConnectionString("DefaultConnection");
            
            services.AddSingleton<ISqlSugarClient>(provider =>
            {
                var config = new ConnectionConfig
                {
                    ConnectionString = connectionString,
                    DbType = DbType.Sqlite,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute
                };

                var db = new SqlSugarClient(config);
                
                // 配置实体
                db.CodeFirst.InitTables(
                    typeof(SysUser),
                    typeof(SysRole),
                    typeof(SysMenu),
                    typeof(SysUserRole),
                    typeof(SysRoleMenu)
                );

                return db;
            });

            return services;
        }

        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <param name="db"></param>
        public static void InitializeDatabase(ISqlSugarClient db)
        {
            // 创建表
            db.CodeFirst.InitTables(
                typeof(SysUser),
                typeof(SysRole),
                typeof(SysMenu),
                typeof(SysUserRole),
                typeof(SysRoleMenu)
            );

            // 初始化基础数据
            InitSeedData(db);
        }

        /// <summary>
        /// 初始化种子数据
        /// </summary>
        /// <param name="db"></param>
        private static void InitSeedData(ISqlSugarClient db)
        {
            // 检查是否已有数据
            if (db.Queryable<SysUser>().Any())
                return;

            // 创建默认管理员用户
            var adminUser = new SysUser
            {
                Username = "admin",
                Password = BCrypt.Net.BCrypt.HashPassword("123456"),
                NickName = "管理员",
                Email = "admin@example.com",
                Mobile = "13800138000",
                Status = 1,
                CreateTime = DateTime.Now,
                CreateId = 1,
                IsDeleted = 0,
                LastLoginTime = DateTime.Now
            };
            db.Insertable(adminUser).ExecuteCommand();

            // 创建默认角色
            var adminRole = new SysRole
            {
                RoleName = "管理员",
                RoleCode = "admin",
                Description = "系统管理员",
                Status = 1,
                CreateTime = DateTime.Now,
                CreateId = 1,
                IsDeleted = 0,
                IsSystem = true,
                DataScope = 1
            };
            db.Insertable(adminRole).ExecuteCommand();

            // 创建默认菜单
            var systemMenu = new SysMenu
            {
                ParentId = 0,
                MenuName = "系统管理",
                MenuType = "M",
                Path = "/system",
                Component = "",
                Icon = "system",
                OrderNum = 1,
                Status = 1,
                Visible = 1,
                IsFrame = 0,
                IsCache = 0,
                Perms = "",
                CreateTime = DateTime.Now,
                CreateId = 1,
                IsDeleted = 0,
                Remark = "系统管理",
            };
            db.Insertable(systemMenu).ExecuteCommand();

            var menuMenu = new SysMenu
            {
                ParentId = 1,
                MenuName = "菜单管理",
                MenuType = "C",
                Path = "/system/menu",
                Component = "system/menu/index",
                Icon = "tree-table",
                OrderNum = 1,
                Status = 1,
                Visible = 1,
                IsFrame = 0,
                IsCache = 0,
                Perms = "system:menu:list",
                CreateTime = DateTime.Now,
                CreateId = 1,
                IsDeleted = 0,
                Remark = "菜单管理",
            };
            db.Insertable(menuMenu).ExecuteCommand();

            var roleMenu = new SysMenu
            {
                ParentId = 1,
                MenuName = "角色管理",
                MenuType = "C",
                Path = "/system/role",
                Component = "system/role/index",
                Icon = "peoples",
                OrderNum = 2,
                Status = 1,
                Visible = 1,
                IsFrame = 0,
                IsCache = 0,
                Perms = "system:role:list",
                CreateTime = DateTime.Now,
                CreateId = 1,
                IsDeleted = 0,
                Remark = "角色管理",
            };
            db.Insertable(roleMenu).ExecuteCommand();

            var userMenu = new SysMenu
            {
                ParentId = 1,
                MenuName = "账户管理",
                MenuType = "C",
                Path = "/system/user",
                Component = "system/user/index",
                Icon = "user",
                OrderNum = 3,
                Status = 1,
                Visible = 1,
                IsFrame = 0,
                IsCache = 0,
                Perms = "system:user:list",
                CreateTime = DateTime.Now,
                CreateId = 1,
                IsDeleted = 0,
                Remark = "账户管理",
            };
            db.Insertable(userMenu).ExecuteCommand();


            // 分配用户角色
            var userRole = new SysUserRole { UserId = 1, RoleId = 1 };
            db.Insertable(userRole).ExecuteCommand();

            // 分配角色菜单权限
            var roleMenus = new List<SysRoleMenu>
            {
                new SysRoleMenu { RoleId = 1, MenuId = 1 },
                new SysRoleMenu { RoleId = 1, MenuId = 2 },
                new SysRoleMenu { RoleId = 1, MenuId = 3 },
                new SysRoleMenu { RoleId = 1, MenuId = 4 }
            };
            db.Insertable(roleMenus).ExecuteCommand();
        }
    }
}